﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Provider;
using System.Management.Automation;
using System.Reflection;

using Cognifide.PowerShell.Shell.Commands;
using Cognifide.PowerShell.Shell.Provider;

using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Globalization;
using Sitecore.Publishing;
using Sitecore.Publishing.Pipelines.PublishItem;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web.UI.Sheer;

namespace Cognifide.PowerShell.Shell
{
    [Cmdlet("Execute", "ShellCommand", SupportsShouldProcess = true, DefaultParameterSetName = "Item")]
    public class ExecuteShellCommandCommand : BaseCommand
    {
        [ValidatePattern(@"[\*\?\[\]\-0-9a-zA-Z_]+\:[\*\?\[\]\-0-9a-zA-Z_]+")]
        [Parameter(Position = 0, Mandatory = true)]
        public string Name { get; set; }

        [Parameter(ValueFromPipeline = true, Position = 1)]
        public Item Item { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                Item item = this.Item;
                //Sitecore.Context.SetActiveSite("shell");
                //Sitecore.Context.ClientPage = new ClientPage();
                CommandContext context = new CommandContext(item);
                context.RibbonSourceUri = item.Uri;
                //MessageCommand command = new MessageCommand(Message.Parse(this, Name));
                Command command = CommandManager.GetCommand(Name);
                if (command == null)
                    return;
                command.Execute(context);
                //Sitecore.Context.SetActiveSite("website");
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Error while executing '{0}' command", ex, this);
                throw;
            }
        }
    }
}

